#include <xp/net/socket.h>
#include <xp/bas/memory.h>
#include <xp/bas/stdio.h>
#include <xp/bas/locale.h>
#include <xp/bas/errno.h>
#include <xp/bas/endian.h>

#ifdef __linux
#include <mcheck.h>
#endif

int xp_main ()
{
	xp_sckhnd_t x;
	xp_byte_t buf[1000];
	xp_ssize_t n;

#ifdef __linux
	mtrace ();
#endif

	xp_setlocale ();

	if ((x = xp_sckopen (AF_INET, SOCK_STREAM, 0)) == XP_SCKHND_INVALID) {
		xp_printf (XP_TEXT("cannot create socket\n"));
		return -1;
	}

	xp_sckadrin4_t addr;
	xp_memset (&addr, 0, xp_sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	//addr.sin_addr.s_addr = inet_addr("192.168.123.100");
	addr.sin_port = xp_hton16(22);

	for (;;) {
		if ((n = xp_sckconn(x, 
			(xp_sckadr_t*)&addr, xp_sizeof(addr), 5000)) == -1) {
			printf ("cannot connect %d %d\n", n, xp_errno);
			break;
		}

		if ((n = xp_sckrecv (x, buf, xp_sizeof(buf), 0, -1)) <= -1) {
			printf ("cannot receive %d %d\n", n, xp_errno);
			break;
		}

		buf[n] = '\0';
		printf ("%s", buf);

		if ((n = xp_sckrecv (x, buf, xp_sizeof(buf), 0, 5000)) <= -1) {
			printf ("cannot receive %d %d\n", n, xp_errno);
			break;
		}

		buf[n] = '\0';
		printf ("%s", buf);
	}

	printf ("close: %d\n", xp_sckclose (x));
	return 0;
}

